const express = require("express");
const multer = require("multer");
const sharp = require("sharp");
const path = require("path");
const fs = require("fs");

const router = express.Router();

const uploadPath = path.join(__dirname, "../public/uploads");
const SIZES = {
  small: 300,
  medium: 800,
};
const sizes = [SIZES.small, SIZES.medium]; // 定义需要生成的图片尺寸

// 设置存储配置
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath);
    }
    cb(null, uploadPath);
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + path.extname(file.originalname));
  },
});

const upload = multer({ storage: storage });

// 图片处理函数
const processImage = (imagePath, sizes) => {
  return new Promise((resolve, reject) => {
    const results = {};
    const processSizes = sizes.map((size) => {
      return new Promise((innerResolve, innerReject) => {
        sharp(imagePath)
          .metadata()
          .then((metadata) => {
            const dimensions = {
              width: size,
              height: Math.round((metadata.height / metadata.width) * size),
            };
            const outputPath = path.join(
              uploadPath,
              `${Date.now()}_${size}${path.extname(imagePath)}`
            );
            results[size] = outputPath;
            sharp(imagePath)
              .resize(dimensions.width, dimensions.height)
              .toFile(outputPath)
              .then(() => innerResolve())
              .catch((err) => innerReject(err));
          })
          .catch((err) => innerReject(err));
      });
    });

    Promise.all(processSizes)
      .then(() => resolve(results))
      .catch((err) => reject(err));
  });
};

// 图片上传路由
router.post("/", upload.single("image"), async (req, res) => {
  try {
    const imagePath = req.file.path;
    const image = await processImage(imagePath, sizes);

    // 删除多余的路径 返回 uploads/abc.jpg
    const prefix = path.join(uploadPath, "../");
    const data = {
      small: image[SIZES.small].replace(prefix, ""),
      medium: image[SIZES.medium].replace(prefix, ""),
    };

    // 删除原始上传文件（可选）
    fs.unlinkSync(imagePath);

    res.json({
      success: true,
      data,
    });
  } catch (err) {
    console.error(err);
    res.status(500).json({
      success: false,
      message: "Error processing image",
    });
  }
});

// app.listen(port, () => {
//   console.log(`Server is running on http://localhost:${port}`);
// });

const outputPath = path.join(uploadPath, `1.png`);
console.log("🚀 ~ outputPath:", outputPath);
console.log("🚀 ~ __dirname:", path.join(__dirname, "../"));

module.exports = router;
